package com.gitee.wsl.mathematics.geometry.d2.curve.equation

import com.gitee.wsl.mathematics.coordinate.d2.Point2D
import kotlin.math.max
import kotlin.math.pow


class InterpolationGenerator(var points: MutableList<Point2D> = mutableListOf(), // this vector will hold quadratic graph points
                             // this vector will hold the quadratic graph equations
                             var equations: MutableList<QuadraticEquation> = ArrayList(max(points.size - 1,0))) {


    fun generateEquations() {
        check(points.size >= 3) { "You need three points minimum to generate the interpolation equations." }

        equations.clear()

        var fPoint = points[0]
        var sPoint = points[1]

        var a: Double
        var b: Double
        var c: Double

        val solver = ThreeEquationSystemSolver()
        var lastEquation: QuadraticEquation

        a = 0.0
        b = (fPoint.y - sPoint.y) / (fPoint.x - sPoint.x)
        c = fPoint.y - fPoint.x * b

        equations.add(QuadraticEquation(a, b, c))

        for (i in 1 until points.size - 1) {
            fPoint = points[i]
            sPoint = points[i + 1]
            lastEquation = equations.last()

            solver.setFirstEquation(fPoint.x.pow(2.0), fPoint.x, 1.0, fPoint.y)
            solver.setSecondEquation(sPoint.x.pow(2.0), sPoint.x, 1.0, sPoint.y)
            solver.setThirdEquation(
                2 * fPoint.x,
                1.0,
                0.0,
                2 * fPoint.x * lastEquation.a + lastEquation.b
            )

            solver.solve()

            a = solver.firstVariable
            b = solver.secondVariable
            c = solver.thirdVariable

            equations.add(QuadraticEquation(a, b, c))
        }
    }

    fun addPoint(p:Point2D){
        points.add(p)
    }

}
